import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import qs from 'qs'

// create an axios instance
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		if (store.getters.token) config.headers['Access-Token'] = getToken()
        // format: ids[0]=10001&ids[1]=10002
        // config.data = qs.stringify(config.data)

        // format: ids[]=10001&ids[]=10002
		// config.data = qs.stringify(config.data, {arrayFormat: 'brackets'})
		return config
	},
	error => {
		// do something with request error
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data

		if (res.err_code !== 0) {
			Message({
				message: res.err_msg || 'Api Error',
				type: 'error',
				duration: 3 * 1000
			})

			if (res.err_code === 10001) {
				MessageBox.confirm('未登录或已超时，请重新登录', '确认', {
					confirmButtonText: '重新登录',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					store.dispatch('user/resetToken').then(() => {
						location.reload()
					})
				})
			}
			return Promise.reject(new Error(res.err_msg || 'Api Error'))
		} else {
			return res
		}
	},
	error => {
        // debugger
		Message({
			message: error.err_msg || error.message,
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service
